 package com.itic.mobile.order;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.user.persistence.model.SysUser;
import com.itic.appbase.framework.annotation.CheckLogin;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.xcx.utils.WeixinUtil;
import com.itic.appbase.framework.xcx.vo.WXPayResult;
import com.itic.mobile.base.BaseMobile;
import com.itic.system.market.productitem.persistence.model.ProductItem;
import com.itic.system.market.productitem.service.ProductItemService;
import com.itic.system.market.viptype.persistence.model.VipType;
import com.itic.system.market.viptype.service.VipTypeService;
import com.itic.system.order.orderproductitem.persistence.model.OrderProductItem;
import com.itic.system.order.orderproductitem.service.OrderProductItemService;
import com.itic.system.order.ordervip.service.OrderVipService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/mobile/order")
public class OrderMobile extends BaseMobile {
	@Autowired
	private VipTypeService vipTypeService;
	@Autowired
	private ProductItemService productItemService;
	@Autowired
	private OrderProductItemService orderProductItemService;
	@Autowired
	private OrderVipService orderVipService;
	
	//private static String VIP="vip";
	
	//private static String PRODUCT="product";

	// 商品过滤字段
	protected static String[] ignoreCategoryProperties = new String[] { "id", "createUser", "isEffective", "updateTime",
			"note", "createTime", "orgCode", "reorder", "parentId" };

	// 商品过滤字段
	protected static String[] ignoreProductProperties = new String[] { "id", "createUser", "isEffective", "updateTime",
			"note", "createTime", "orgCode", "reorder", "parentId" };

	// 商品过滤字段
	protected static String[] ignoreProductItemProperties = new String[] {  "createUser", "isEffective",
			"updateTime", "note", "createTime", "orgCode", "reorder", "productId","fee","isVipVideo","summary","videoUrl" };

	/**
	 * 商品列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/preOrder") 
	@ResponseBody
	public Map<String, Object> categorys(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			//resultMap.put(DATA, dataMap);
			errorCode = SUCCESS_ERROR_CODE; 
			errorMsg = SUCCESS_ERROR_MSG; 
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "categorys", e.toString(), "商品分类列表信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	
	

	/**
	 * 商品列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/order")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request, HttpServletResponse response, String categoryCode,String keyword) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			resultMap.put(DATA, getProductList(request, categoryCode, keyword));
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "list", e.toString(), "商品列表", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 商品详情
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/accountPay")
	@ResponseBody
	@CheckLogin
	public Map<String, Object> detail(HttpServletRequest request, HttpServletResponse response,String payType,String payId ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			
			if( StringHelper.isNotBlank(payType) && StringHelper.isNotBlank(payId) ){
				SysUser user = getRequestUser(request);
				if( "vip".equals(payType) ){
					VipType vipType = vipTypeService.get(payId);
					if( null != vipType ){
						//生成一个订单
						orderVipService.accountPay(user,vipType);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = VIP_TYPE_ERROR_CODE;
						errorMsg = VIP_TYPE_ERROR_MSG;
					}
				}
				if( "product".equals(payType) ){
					OrderProductItem orderProductItem = orderProductItemService.get(payId);
					if( null != orderProductItem ){
						orderProductItemService.accountPay(user,orderProductItem);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = PRODUCT_ITEM_ID_ERROR_CODE;
						errorMsg = PRODUCT_ITEM_ID_ERROR_MSG;
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "detail", e.toString(), "商品详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	
	/**
	 * 微信支付VIP会员
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/wxPayVip")
	@ResponseBody
	@CheckLogin
	public Map<String, Object> wxPayVip(HttpServletRequest request, HttpServletResponse response, String vipTypeId ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if( StringHelper.isNotBlank(vipTypeId) ){
				SysUser user = getRequestUser(request);
				if( StringHelper.isNotBlank(user.getOpenId()) ){
					VipType vipType = vipTypeService.get(vipTypeId);
					if( null != vipType ){
						//生成一个订单
						WXPayResult wxPayResult = orderVipService.addOrderAndReturnWxPay(user,vipType);;
						if("SUCCESS".equals(wxPayResult.getError_code())) {
							JSONObject obj = wxPayResult.getResult();
							resultMap.put(DATA, obj);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else {
							//若不成功 返回微信调起失败
							errorCode = WX_PAY_NOT_SUCCESS_CODE;
							errorMsg = WX_PAY_NOT_SUCCESS_MSG;
						}
					}else{
						errorCode = VIP_TYPE_ERROR_CODE;
						errorMsg = VIP_TYPE_ERROR_MSG;
					}
				}else{
					errorCode = OPENID_ERROR_CODE;
					errorMsg = OPENID_ERROR_MSG;
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "wxPayVip", e.toString(), "微信支付VIP会员", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	
	/**
	 * 微信支付商品项信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/wxPayProductItem")
	@ResponseBody
	@CheckLogin
	public Map<String, Object> wxPayProductItem(HttpServletRequest request, HttpServletResponse response, String productItemId ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if( StringHelper.isNotBlank(productItemId) ){
				SysUser user = getRequestUser(request);
				if( StringHelper.isNotBlank(user.getOpenId()) ){
					ProductItem productItem = productItemService.get(productItemId);
					if( null != productItem ){
						//生成一个订单
						WXPayResult wxPayResult = orderProductItemService.addOrderAndReturnWxPay(user,productItem);;
						if("SUCCESS".equals(wxPayResult.getError_code())) {
							JSONObject obj = wxPayResult.getResult();
							//obj.put("orderNo", orderNo);
							resultMap.put(DATA, obj);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else {
							//若不成功 返回微信调起失败
							errorCode = WX_PAY_NOT_SUCCESS_CODE;
							errorMsg = WX_PAY_NOT_SUCCESS_MSG;
						}
					}else{
						errorCode =  PRODUCT_ITEM_ERROR_CODE;
						errorMsg = PRODUCT_ITEM_ERROR_MSG;
					}
				}else{
					errorCode = OPENID_ERROR_CODE;
					errorMsg = OPENID_ERROR_MSG;
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "wxPayProductItem", e.toString(), "微信支付商品项信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	/**
	 * vip支付VIP成功回调
	 * @param request
	 * @return
	 */
	@RequestMapping(value="vipSuccess")
	public String success(HttpServletRequest request) {
		
		//用于处理结束后返回的xml
        StringBuffer sb = new StringBuffer();
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = request.getInputStream();
            out = new ByteArrayOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while((len = in.read(b)) != -1){
                out.write(b, 0, len);
            }
            //将流 转为字符串
            String result = new String(out.toByteArray(), "utf-8");
            Map<String, String> map = WeixinUtil.getNotifyUrl(result);
            String return_code = map.get("return_code").toString().toUpperCase();
           /* String attach = map.get("attach").toString().toUpperCase();
            String key = "&key="+attach;*/
            if(return_code.equals("SUCCESS")){
                //进行签名验证，看是否是从微信发送过来的，防止资金被盗
                //if(WeixinUtil.verifyWeixinNotify(map, key)){
                    //签名验证成功后按照微信要求返回的xml
                	sb.append("<xml>");
                	sb.append("<return_code><![CDATA[SUCCESS]]></return_code>");
                	sb.append("<return_msg><![CDATA[OK]]></return_msg>");
                	sb.append("</xml>");
                	//TODO 处理自己的订单业务
                	//支付完成时间
                	String finishTime = map.get("time_end");
                	//订单号
                	String out_trade_no = map.get("out_trade_no");
                	//实付款
                	String total_fee = map.get("total_fee");
                	//信支付订单号
                	String transaction_id = map.get("transaction_id");
                	//用户openId
                	String openid = map.get("openid");
                	//商家appId
                	String appid = map.get("appid");
                	//商户号
                	String mch_id = map.get("mch_id");
                	orderVipService.paySuccessDealOrder(appid, out_trade_no, finishTime, total_fee, transaction_id, openid, mch_id);
                    return sb.toString();
                //}
            }else{
            	sb.append("<xml>");
            	sb.append("<return_code><![CDATA[FAIL]]></return_code>");
            	sb.append("<return_msg><![CDATA[sign check error]]></return_msg>");
            	sb.append("</xml>");
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
				out.close();
				 in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
           
        }
        sb.append("<xml>");
    	sb.append("<return_code><![CDATA[FAIL]]></return_code>");
    	sb.append("<return_msg><![CDATA[xml error]]></return_msg>");
    	sb.append("</xml>");
        return sb.toString();
		
		
	}
	
	/**
	 * 微信支付商品项回调
	 * @param request
	 * @return
	 */
	@RequestMapping(value="productItemSuccess")
	public String productItemSuccess(HttpServletRequest request) {
		
		//用于处理结束后返回的xml
        StringBuffer sb = new StringBuffer();
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = request.getInputStream();
            out = new ByteArrayOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while((len = in.read(b)) != -1){
                out.write(b, 0, len);
            }
            //将流 转为字符串
            String result = new String(out.toByteArray(), "utf-8");
            Map<String, String> map = WeixinUtil.getNotifyUrl(result);
            String return_code = map.get("return_code").toString().toUpperCase();
           /* String attach = map.get("attach").toString().toUpperCase();
            String key = "&key="+attach;*/
            if(return_code.equals("SUCCESS")){
                //进行签名验证，看是否是从微信发送过来的，防止资金被盗
                //if(WeixinUtil.verifyWeixinNotify(map, key)){
                    //签名验证成功后按照微信要求返回的xml
                	sb.append("<xml>");
                	sb.append("<return_code><![CDATA[SUCCESS]]></return_code>");
                	sb.append("<return_msg><![CDATA[OK]]></return_msg>");
                	sb.append("</xml>");
                	//TODO 处理自己的订单业务
                	//支付完成时间
                	String finishTime = map.get("time_end");
                	//订单号
                	String out_trade_no = map.get("out_trade_no");
                	//实付款
                	String total_fee = map.get("total_fee");
                	//信支付订单号
                	String transaction_id = map.get("transaction_id");
                	//用户openId
                	String openid = map.get("openid");
                	//商家appId
                	String appid = map.get("appid");
                	//商户号
                	String mch_id = map.get("mch_id");
                	orderProductItemService.paySuccessDealOrder(appid, out_trade_no, finishTime, total_fee, transaction_id, openid, mch_id);
                    return sb.toString();
                //}
            }else{
            	sb.append("<xml>");
            	sb.append("<return_code><![CDATA[FAIL]]></return_code>");
            	sb.append("<return_msg><![CDATA[sign check error]]></return_msg>");
            	sb.append("</xml>");
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
				out.close();
				 in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
           
        }
        sb.append("<xml>");
    	sb.append("<return_code><![CDATA[FAIL]]></return_code>");
    	sb.append("<return_msg><![CDATA[xml error]]></return_msg>");
    	sb.append("</xml>");
        return sb.toString();
		
		
	}
}